/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.standardcloud.swagger;

import com.spring4all.swagger.SwaggerProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @project-name:standard-cloud
 * @package-name:com.hyts.standardcloud.swagger
 * @author:LiBo/Alex
 * @create-date:2020-01-02 23:07
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@EnableConfigurationProperties(SwaggerProperties.class)
@EnableSwagger2
@ConditionalOnClass(value = {Swagger.class})
@ConditionalOnExpression("${swagger.enable:true}") // 根据配置决定是否最终启用 Swagger
@Configurable
public class SwaggerBeanConfiguration extends WebMvcConfigurerAdapter {

    /**
     * swagger 属性对象操作
     */
    @Autowired(required = false)
    SwaggerProperties swaggerProperties;


    /**
     * 创建rest api文档服务
     * @return
     */
    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .host(swaggerProperties.getHost());
        docket.select().paths(PathSelectors.any())
                       .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                       .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                       .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                       .build()
                       .apiInfo(apiInfo())
                       .globalOperationParameters(parameters())
                       .globalResponseMessage(RequestMethod.GET,
                        newArrayList(new ResponseMessageBuilder()
                                        .code(500)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_BAD_MESSAGE,RequestMethod.GET.name()))
                                        .build(),
                                new ResponseMessageBuilder()
                                        .code(200)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_OK_MESSAGE,RequestMethod.GET.name()))
                                        .build()))
                       .globalResponseMessage(RequestMethod.POST,
                        newArrayList(new ResponseMessageBuilder()
                                        .code(500)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_BAD_MESSAGE,RequestMethod.POST.name()))
                                        .build(),
                                new ResponseMessageBuilder()
                                        .code(200)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_OK_MESSAGE,RequestMethod.POST.name()))
                                        .build()))
                       .globalResponseMessage(RequestMethod.DELETE,
                        newArrayList(new ResponseMessageBuilder()
                                        .code(500)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_BAD_MESSAGE,RequestMethod.DELETE.name()))
                                        .build(),
                                new ResponseMessageBuilder()
                                        .code(200)
                                        .message(String.format(SwaggerBaseConfiguration.
                                                DEFAULT_STATIC_OK_MESSAGE,RequestMethod.DELETE.name()))
                                        .build()))
                       .enable(swaggerProperties.getEnabled());
        return docket;
    }

    /**
     * 构建api-info基本信息操作
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .description(swaggerProperties.getDescription())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .version(swaggerProperties.getVersion())
                .contact(swaggerProperties.getContact().getName())
                .build();
    }

    /**
     * 操作相关的ui配置服务
     * @return
     */
    @Bean
    UiConfiguration uiConfig() {
        //UiConfigurationBuilder.builder().validatorUrl("list").
        return new UiConfiguration(null, "list", "alpha",
                "schema",
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false,
                true, 60000L);
    }

    /**
     * 参数列表信息（全局）
     * @return
     */
    private List<Parameter> parameters() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();
        parameterBuilder.name("Authorization")
                .description("认证信息基础信息对象模型")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).
                build();
        parameters.add(parameterBuilder.build());
        return parameters;
    }

    /**
     * swagger 文档配置服务对象
     * @return
     */
    @Primary
    @Bean
    public SwaggerDocsConfiguration swaggerDocsConfiguration(){
        return new SwaggerDocsConfiguration();
    }



    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/META-INF/resources/templates/");
    }


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/swagger","/swagger-ui.html");
        registry.addRedirectViewController("/doc","/doc.html");
    }
}
